# -*- coding: UTF-8 -*-


from .models import Model as BaseModel


class Environment(object):
    def __init__(self, context=None, web=None):
        self._context = context
        self.web = web

    @property
    def session(self):
        info = self.web.session.session_info
        if not info:
            info = {}

        return info

    @property
    def uid(self):
        session = self.session
        return session.get('uid')

    @property
    def context(self):
        context = self._context
        if context:
            return context

        ctx = self.web.session.user_context
        self._context = ctx
        return self._context

    def model(self, model, fields=None):
        if not fields:
            return self._create_model_class(model)
        elif isinstance(fields, (list, tuple)):
            Model = self._create_model_class(model)
            print('env model,', self)
            print('env model,', self.web)
            print('env model,', self.web.session)
            # print('env model,', self.context)
            fields_info = Model.fields_get(fields)
            Model._updata_fields(fields_info)
            return Model
        else:
            return self._create_model_class(model, fields)

    def _create_model_class(self, model, fields=None):
        if not fields:
            fields = {}

        fields = fields.copy()

        BaseModel2 = BaseModel
        env1 = self

        class Model(BaseModel2):
            _env = env1
            _model = model
            _fields = fields

            @classmethod
            def _updata_fields(cls, fields2):
                cls._fields.update(fields2)

        return Model
